package com.example.knowledgeget1.KnowtCommon.Service;

import com.example.knowledgeget1.KnowtCommon.Entity.Student;
import com.example.knowledgeget1.KnowtCommon.Entity.Teacher;
import com.example.knowledgeget1.KnowtCommon.Repository.TeacherRepository;
import com.example.knowledgeget1.KnowtCommon.Response.StudentLoginResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

@Service
public class TeacherService {
    @Autowired
    private TeacherRepository teacherRepository;

    // 创建新教师
    public Teacher createTeacher(Teacher teacher) {
        return teacherRepository.save(teacher);
    }

    // 获取所有教师
    public List<Teacher> getAllTeachers() {
        return teacherRepository.findAll();
    }

    // 通过ID获取单个教师
    public Teacher getTeacherById(Long id) {
        Optional<Teacher> teacher = teacherRepository.findById(id);
        return teacher.orElse(null);
    }

    // 更新教师信息
    public Teacher updateTeacher(Long id, Teacher teacherDetails) {
        Teacher teacher = getTeacherById(id);
        if (teacher != null) {
            teacher.setTeaName(teacherDetails.getTeaName());
            teacher.setTeaPwd(teacherDetails.getTeaPwd());
            // 更新其他字段...
            teacherRepository.save(teacher);
        }
        return teacher;
    }

    // 删除教师
    public void deleteTeacher(Long id) {
        teacherRepository.deleteById(id);
    }

    // 验证教师账号和密码，并返回包含账号和token的响应对象
    public Map<String, String> teacherLoginAndGetToken(Long teaId, String teaPwd) {
        Optional<Teacher> teacher = teacherRepository.findById(teaId);
        if (teacher.isPresent() && teacher.get().getTeaPwd().equals(teaPwd)) {
            String token = generateToken(); // 生成token
            return Map.of("teaId", String.valueOf(teaId), "token", token);
        }
        return null; // 验证失败，返回null
    }

    // 生成token
    private String generateToken() {
        return UUID.randomUUID().toString(); // 使用UUID生成唯一的token
    }
}